package com.papercutting.platform.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.papercutting.platform.entity.Config;
import com.papercutting.platform.repository.ConfigRepository;
import com.papercutting.platform.service.ConfigService;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;

/**
 * 系统配置服务实现类
 */
@Service
public class ConfigServiceImpl implements ConfigService {
    
    private final ConfigRepository configRepository;
    
    public ConfigServiceImpl(ConfigRepository configRepository) {
        this.configRepository = configRepository;
    }
    
    @Override
    public Config save(Config config) {
        if (config.getId() == null) {
            configRepository.insert(config);
        } else {
            configRepository.updateById(config);
        }
        return config;
    }

    @Override
    public Config findById(Long id) {
        return configRepository.selectById(id);
    }

    @Override
    public List<Config> findAll() {
        return configRepository.selectList(null);
    }

    @Override
    public Page<Config> findAll(Pageable pageable) {
        com.baomidou.mybatisplus.extension.plugins.pagination.Page<Config> page =
            new com.baomidou.mybatisplus.extension.plugins.pagination.Page<>(
                pageable.getPageNumber() + 1, pageable.getPageSize());
        com.baomidou.mybatisplus.extension.plugins.pagination.Page<Config> result =
            configRepository.selectPage(page, null);
        return new PageImpl<>(result.getRecords(), pageable, result.getTotal());
    }

    @Override
    public void deleteById(Long id) {
        configRepository.deleteById(id);
    }

    @Override
    public Config findByConfigKey(String configKey) {
        QueryWrapper<Config> wrapper = new QueryWrapper<>();
        wrapper.eq("config_key", configKey);
        return configRepository.selectOne(wrapper);
    }

    @Override
    public Config findByConfigKeyAndIsSystem(String configKey, Boolean isSystem) {
        QueryWrapper<Config> wrapper = new QueryWrapper<>();
        wrapper.eq("config_key", configKey)
               .eq("is_system", isSystem);
        return configRepository.selectOne(wrapper);
    }
}